package com.king.micro.common;


import com.zeus.framework.commons.json.DataTransferObject;
import com.king.micro.common.exception.BusinessException;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author 赵晓光
 *         created 2017/11/10 15:16
 *         copyright 2017 micro
 * @FileName: CglibProxy.java
 * package: com.king.micro.common
 */
public class CglibProxy implements MethodInterceptor {

    private Enhancer enhancer = new Enhancer();

    public Object getProxy(Class clazz) {
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();

    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("------ 前面 --------");
        System.out.println("22222222222" + o.getClass().getSuperclass().getName());
        Object message = null;
        try {
              message = methodProxy.invokeSuper(o,args);
        } catch (Exception var21) {
            message = this.handException(var21);
        }
        System.out.println("------ 后面 --------");
        return message;
    }

    public Object handException(Exception e) {
        if(e instanceof BusinessException) {
            BusinessException exception1 = (BusinessException)e;
            return getDTOFromException(exception1.getCode(),exception1.getMessage());
        }  else {
            return handleErrorException(e);
        }
    }

    private String getDTOFromException(int code, String message) {
        DataTransferObject dataTransferObject = new DataTransferObject();
        dataTransferObject.setCode(code);
        dataTransferObject.setMsg(message);
        return dataTransferObject.toJsonString();
    }

    /**
     * 处理系统异常
     * @param e
     * @return
     */
    private String handleErrorException(Exception e){
        return getDTOFromException(DataTransferObject.SYS_ERROR, "服务错误");
    }
}
